/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 * */

// AmzServer - Tototoy's server model.
// Author: tonyjobmails@gmail.com (tonyhack).
//
// Define class Log.
//
// The class Log is a Realization of log,
// It provide five kinds of log level - debug, info, warn, error and fatal.
//

#include <string.h>
#include <stdio.h>
#include <time.h>

#include "log_lite.h"
#include "variable_parameter.h"

#define LOG_MAX_LEN 2048

namespace amz {

LogLite::LogLite(const char *log_file_name) {

  strncpy(this->log_file_name_, log_file_name, sizeof(this->log_file_name_));
}

void LogLite::SetLogName(const char *log_file_name) {

  strncpy(this->log_file_name_, log_file_name, sizeof(this->log_file_name_));
}

void LogLite::Debug(const char *contect, ...) {

  char buff[LOG_MAX_LEN + 1];
  bzero(buff, sizeof(buff));

  GET_VARIABLE_PARAMETERS(buff, sizeof(buff), contect);

  this->Log("Debug", buff);
}

void LogLite::Info(const char *contect, ...) {

  char buff[LOG_MAX_LEN + 1];
  bzero(buff, sizeof(buff));

  GET_VARIABLE_PARAMETERS(buff, sizeof(buff), contect);

  this->Log("Info", buff);
}

void LogLite::Warn(const char *contect, ...) {

  char buff[LOG_MAX_LEN + 1];
  bzero(buff, sizeof(buff));

  GET_VARIABLE_PARAMETERS(buff, sizeof(buff), contect);

  this->Log("Warn", buff);
}

void LogLite::Error(const char *contect, ...) {

  char buff[LOG_MAX_LEN + 1];
  bzero(buff, sizeof(buff));

  GET_VARIABLE_PARAMETERS(buff, sizeof(buff), contect);

  this->Log("Error", buff);
}

void LogLite::Fatal(const char *contect, ...) {

  char buff[LOG_MAX_LEN + 1];
  bzero(buff, sizeof(buff));

  GET_VARIABLE_PARAMETERS(buff, sizeof(buff), contect);

  this->Log("Fatal", buff);
}

void LogLite::Log(const char *level, const char *content) {

  time_t now;
  now = time(NULL);

  tm *tm_now = localtime(&now);
  char current_time[32] = {0};
  strftime(current_time, sizeof(current_time), "%Y-%m-%d %H:%M:%S", tm_now);

  FILE *fp = fopen(this->log_file_name_, "a");
  if(fp != NULL) {
    fprintf(fp, "[%s][%s]:%s\n", current_time, level, content);
    fclose(fp);
  }
}

}  // namespace amz

